package tss

import (
	"encoding/json"
	"github.com/julienschmidt/httprouter"
	"net/http"
	"os"
	"path"
	"sort"
)

type Common struct {
	Success   bool   `json:"success"`   // 是否成功
	ErrorCode int    `json:"errorCode"` // 错误码
	ErrorMsg  string `json:"errorMsg"`  // 错误信息
	Data      any    `json:"data"`      // 数据
}

func (tss *Tss) dirListApi(writer http.ResponseWriter, request *http.Request, ps httprouter.Params) {
	filePath := ps.ByName("filepath")
	localPath := path.Join(tss.StoragePath, filePath)

	fileInfo, err := os.Stat(localPath)
	if os.IsNotExist(err) {
		responseError(writer, 404, "File or directory does not exist")
		return
	}

	fileArray := make([]File, 0)
	if !fileInfo.IsDir() {
		fileArray = append(fileArray, File{
			Dir:  false,
			Link: filePath,
			Name: fileInfo.Name(),
			Size: formatFileSize(fileInfo.Size()),
		})
		responseOk(writer, fileArray)
		return
	}

	files, err := os.ReadDir(path.Join(tss.StoragePath, filePath))
	if err != nil {
		http.Error(writer, "Unable to read directory", http.StatusInternalServerError)
		return
	}

	var directories, regularFiles []File

	for _, file := range files {
		name := file.Name()
		// Get file info to retrieve modification time and size
		fileInfo, err := file.Info()
		if err != nil {
			http.Error(writer, "Unable to retrieve file info", http.StatusInternalServerError)
			return
		}
		modTime := fileInfo.ModTime().Format("2006-01-02 15:04:05")
		size := fileInfo.Size()
		fileData := File{
			Name:    name,
			Size:    formatFileSize(size),
			ModTime: modTime,
			Link:    path.Join(filePath, name),
			Dir:     fileInfo.IsDir(),
		}

		if fileInfo.IsDir() {
			directories = append(directories, fileData)
		} else {
			regularFiles = append(regularFiles, fileData)
		}
	}

	// Sort directories and files by name
	sort.Slice(directories, func(i, j int) bool {
		return directories[i].Name < directories[j].Name
	})
	sort.Slice(regularFiles, func(i, j int) bool {
		return regularFiles[i].Name < regularFiles[j].Name
	})

	// Append directories first, then files
	fileArray = append(fileArray, directories...)
	fileArray = append(fileArray, regularFiles...)

	// If the request is for JSON, return the data as JSON
	responseOk(writer, fileArray)
}

func responseOk(writer http.ResponseWriter, data any) {
	writer.Header().Set("Content-Type", "application/json")
	writer.WriteHeader(http.StatusOK)
	jsonData, _ := json.Marshal(Common{
		Success: true,
		Data:    data,
	})
	writer.Write(jsonData)
}

func responseError(writer http.ResponseWriter, code int, msg string) {
	writer.Header().Set("Content-Type", "application/json")
	writer.WriteHeader(http.StatusOK)
	jsonData, _ := json.Marshal(Common{
		Success:   false,
		ErrorCode: code,
		ErrorMsg:  msg,
	})
	writer.Write(jsonData)
}
